<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
	<xsl:output method="xml" version="1.0" encoding="UTF-16"  indent="yes"/>
	<!--
		Version 1.5 02/2006
		changed the shema of the formdata xml document fragment
		added the "Field" element so for backward compatibilty we 
		must use a "choose" to determine which schema we are working
		with
	-->
	<xsl:template match="/">
		<FormDataSet>
			<xsl:apply-templates select="//Post"/>
		</FormDataSet>
	</xsl:template>

	<xsl:template match="Post">
		<FormResults>
			<xsl:element name="FormDataID">
				<xsl:value-of select="FormDataID"/>
			</xsl:element>
			<xsl:apply-templates select="FormData/FormResults"/>
		</FormResults>
	</xsl:template>

	<xsl:template match="FormResults">
		<xsl:element name="Submit_Date">
			<xsl:value-of select="@Date"/>
		</xsl:element>
		<xsl:if test="Submitted_By !=''">
			<xsl:element name="Submitted_By">
				<xsl:value-of select="Submitted_By"/>
			</xsl:element>
		</xsl:if>
		<xsl:choose>
			<xsl:when test="count(//Field)=0">
				<xsl:apply-templates select="Question"/>
			</xsl:when>
			<xsl:when test="count(Pages)=0">
				<xsl:apply-templates select="Field"/>
			</xsl:when>
			<xsl:otherwise>
				<xsl:apply-templates select="Pages/Page/Field"/>
			</xsl:otherwise>
		</xsl:choose>
	</xsl:template>

	<xsl:template match="Question">
		<xsl:choose>
			<xsl:when test="text()=''">
				<xsl:element name="NoName">
					<xsl:apply-templates select="Answers/Answer"/>
				</xsl:element>
			</xsl:when>
			<xsl:when test="text()='Date'">
				<xsl:element name="DateDuplicate">
					<xsl:apply-templates select="Answers/Answer"/>
				</xsl:element>
			</xsl:when>
			<xsl:otherwise>
				<xsl:element name="{text()}">
					<xsl:apply-templates select="Answers/Answer"/>
				</xsl:element>
			</xsl:otherwise>
		</xsl:choose>
	</xsl:template>

	<xsl:template match="Field">
		<xsl:variable name="TheQuestion" select="Question"></xsl:variable>
		<xsl:variable name="TheQuestionPos">
			<xsl:value-of select="$TheQuestion"/>
			<xsl:value-of select="position()"/>
		</xsl:variable>
		<xsl:choose>
			<xsl:when test="count(ancestor::FormResults/Field[Question=$TheQuestion] )>1">
				<xsl:element name="{$TheQuestionPos}">
					<xsl:apply-templates select="Answers/Answer"/>
				</xsl:element>
			</xsl:when>
			<xsl:otherwise>
				<xsl:if test="Question!=''">
					<xsl:element name="{Question}">
						<xsl:apply-templates select="Answers/Answer"/>
					</xsl:element>
				</xsl:if>
			</xsl:otherwise>
		</xsl:choose>
	</xsl:template>


	<xsl:template match="Answer">
		<xsl:value-of select="text()"/>
		<xsl:if test="position() &lt; count(ancestor::*/Answer)">,</xsl:if>
	</xsl:template>

</xsl:stylesheet>
